import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import { persistStore, persistReducer } from "redux-persist";
import { storage } from "@/utils/storage";
import { baseApi } from "@/services/api/base";

import themeReducer from "./features/themeSlice";
import userReducer from "./features/userSlice";

const persistConfig = {
  key: "root",
  storage: storage,
  whitelist: ["theme", "user"],
};

const rootReducer = combineReducers({
  theme: themeReducer,
  user: userReducer,
  [baseApi.reducerPath]: baseApi.reducer,
});

export const store = configureStore({
  reducer: persistReducer(persistConfig, rootReducer),
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false,
    }).concat(baseApi.middleware),
});

export const persistor = persistStore(store);
setupListeners(store.dispatch);

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
